package lovemusic.lanou.com.newsmusic.ui.fragment;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import lovemusic.lanou.com.newsmusic.R;
import lovemusic.lanou.com.newsmusic.models.MusicInfo;
import lovemusic.lanou.com.newsmusic.service.PlayMusicService;
import lovemusic.lanou.com.newsmusic.ui.activity.MainActivity;
import lovemusic.lanou.com.newsmusic.ui.adapter.LocalMusicAdapter;
import lovemusic.lanou.com.newsmusic.ui.adapter.OnMoreClickListener;
import lovemusic.lanou.com.newsmusic.utils.FileUtils;
import lovemusic.lanou.com.newsmusic.utils.MusicUtils;
import lovemusic.lanou.com.newsmusic.utils.SystemUtils;
import lovemusic.lanou.com.newsmusic.utils.UIUtils;

/**
 * Created by lanouhn on 2016/9/29.
 */
public class Fragment_localmusic extends Fragment implements OnMoreClickListener{

    private ListView lv_local_nusic;
    private TextView tv_empty;
    private List<MusicInfo> lists= new ArrayList<MusicInfo>();
    private LocalMusicAdapter mAdapter;
    public PlayMusicService mPlayService;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return View.inflate(getActivity(), R.layout.fragent_localmusic,null);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPlayService=((Fragment_music)getParentFragment()).getPlayService();
        Log.d("ss","*****"+mPlayService+" ***************");
        initView();
        init();
    }
    private void init() {

        scanfMusic();
        clickPlayMusic();
    }


    /**
     * 初始化控件
     */
    private void initView() {
        lv_local_nusic= (ListView) getView().findViewById(R.id.lv_local_nusic);
        tv_empty= (TextView) getView().findViewById(R.id.tv_empty);
    }

    /**
     * 扫描本地的歌曲
     */
    public void scanfMusic() {
        lists.addAll(MusicUtils.getMusicDate());
        mAdapter = new LocalMusicAdapter(lists, UIUtils.getContext());
        if (lists.isEmpty()) {
            tv_empty.setVisibility(View.VISIBLE);
        } else {
            tv_empty.setVisibility(View.GONE);
        }
        lv_local_nusic.setAdapter(mAdapter);
        mAdapter.setOnMoreClickListener(this);
    }
    /**
     * 用来给MusicActivity中播放音乐被选中的同步的
     */
    public void onItemPlay() {
        if (mPlayService != null) {
            lv_local_nusic.smoothScrollToPosition(mPlayService.getPlayingPosition());
            mAdapter.setSelecterMusic(mPlayService.getPlayingPosition());
            mAdapter.notifyDataSetChanged();
        }
    }
    /**
     * 点击播放列表中的音乐
     */
    private void clickPlayMusic() {
        lv_local_nusic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPlayService.play(position);
                mAdapter.setSelecterMusic(mPlayService.getPlayingPosition());
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onMoreClick(int position) {
        int itemId = 0;

        final MusicInfo musicInfo = lists.get(position);

//        Toast.makeText(UIUtils.getContext(), musicInfo.getTitle()+" ", Toast.LENGTH_SHORT).show();
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()).
                setTitle(musicInfo.getTitle())
                .setIcon(R.mipmap.icon_dialog);
        if (position == ((Fragment_music)getParentFragment()).getPlayService().getPlayingPosition()) {
            itemId = R.array.local_music_without_delete;
        } else {
            itemId = R.array.local_music_dialog;
        }
        dialog.setItems(itemId, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
//                        分享该歌曲
                        shareMusic(musicInfo);
                        break;
                    case 1:
//                   设为铃声
                        setPhoneRing(musicInfo);
                        break;

                    case 2:
//                     查看歌曲详情
                        infoMusic(musicInfo);

                        break;
                    case 3:
//                        删除歌曲
                        deleteMusic(musicInfo);
                        break;
                }
            }
        }).create();
        dialog.show();
    }

    /**
     * 用Intent来发送音乐的文件来分享音乐
     *
     * @param musicInfo
     */
    private void shareMusic(MusicInfo musicInfo) {
        File file = new File(musicInfo.getUri());
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("audio/*");
        intent.putExtra(Intent.EXTRA_REFERRER, Uri.fromFile(file));
        startActivity(Intent.createChooser(intent, "分享该歌曲"));
    }

    /**
     * 将该音乐设为手机的来电铃声
     *
     * @param musicInfo
     */
    private void setPhoneRing(MusicInfo musicInfo) {
//      获取该音乐在音乐库中的对应的uri
        Uri uri = MediaStore.Audio.Media.getContentUriForPath(musicInfo.getUri());

//       查询音乐文件在媒体库是否存在
        Cursor cursor = getActivity().getContentResolver().query(uri, null,
                MediaStore.MediaColumns.DATA + "=?", new String[]{musicInfo.getUri()}, null);

        if (cursor == null) {
            Toast.makeText(UIUtils.getContext(), "设置铃声失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cursor.moveToFirst() && cursor.getCount() > 0) {
            String _id = cursor.getString(0);
            ContentValues values = new ContentValues();
            values.put(MediaStore.Audio.Media.IS_MUSIC, true);
            values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
            values.put(MediaStore.Audio.Media.IS_ALARM, false);
            values.put(MediaStore.Audio.Media.IS_PODCAST, false);
            values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);

            getContext().getContentResolver().update(uri, values, MediaStore.MediaColumns
                    .DATA + "=?", new String[]{musicInfo.getUri()});

//            通过withAppendedId方法，为该Uri加上ID
            Uri newUri = ContentUris.withAppendedId(uri, Long.valueOf(_id));
//          通过音乐的id为该音乐设置成为铃声
            RingtoneManager.setActualDefaultRingtoneUri(getContext(), RingtoneManager.TYPE_RINGTONE, newUri);
            Toast.makeText(UIUtils.getContext(), "设置铃声成功", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    /**
     * 将该音乐设为闹铃
     *
     * @param musicInfo
     */


    private void setPhoneAlarm(MusicInfo musicInfo) {
//      获取该音乐在音乐库中的对应的uri
        Uri uri = MediaStore.Audio.Media.getContentUriForPath(musicInfo.getUri());

        Cursor cursor = getContext().getContentResolver().query(uri, null,
                MediaStore.MediaColumns.DATA + "=?", new String[]{musicInfo.getUri()}, null);
        if (cursor == null) {
            Toast.makeText(UIUtils.getContext(), "设置闹铃失败", Toast.LENGTH_SHORT).show();
        }
        if (cursor.moveToFirst() && cursor.getCount() > 0) {
            String _ID = cursor.getString(0);
            ContentValues values = new ContentValues();
            values.put(MediaStore.Audio.Media.IS_MUSIC, true);
            values.put(MediaStore.Audio.Media.IS_ALARM, true);

            getContext().getContentResolver().update(uri, values, MediaStore.Audio.Media.DATA
                    + "=?", new String[]{musicInfo.getUri()});
            Uri alarmUri = ContentUris.withAppendedId(uri, Long.valueOf(_ID));
            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        }


    }

    /**
     * 将该音乐的所有信息都显示出来
     * @param musicInfo
     */
    private void infoMusic(MusicInfo musicInfo) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(musicInfo.getTitle());
        StringBuilder sb = new StringBuilder();
        sb.append("歌手:")
                .append(musicInfo.getArtist())
                .append("\n\n")
                .append("专辑:")
                .append(musicInfo.getAlbum())
                .append("\n\n")
                .append("播放时长:")
                .append(SystemUtils.formatTime("mm:ss", musicInfo.getDuration()))
                .append("\n\n")
                .append("文件名称:")
                .append(musicInfo.getFileName())
                .append("\n\n")
                .append("文件大小:")
                .append(FileUtils.b2mb((int) musicInfo.getFileSize()))
                .append("MB")
                .append("\n\n")
                .append("文件的路径:")
                .append(new File(musicInfo.getUri()).getParent());
        dialog.setMessage(sb);
        dialog.create();
        dialog.show();
    }


    private void deleteMusic(final MusicInfo musicInfo) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        String msg = "删除" + musicInfo.getTitle() + "?";
        dialog.setMessage(msg);
        dialog.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ((Fragment_music) getParentFragment()).getPlayService().sMusicList.remove(musicInfo);
                File file = new File(musicInfo.getUri());
                if (file.delete()) {
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + musicInfo.getUri()));
                    getContext().sendBroadcast(intent);
                    lists.clear();
                    ((Fragment_music) getParentFragment()).getPlayService().updateMusicList();
                    ((Fragment_music) getParentFragment()).getPlayService().updatePlayingPosition();
                    lists.addAll(((Fragment_music)getParentFragment()).getPlayService().getMusicList());
                    mAdapter.notifyDataSetChanged();
                }

            }
        }).setNegativeButton("取消", null).create();

        dialog.show();
    }

}
